<template>
  <div class="login">
    <!-- <Nav></Nav> -->
    <el-main>
      <el-form ref="form" label-width="80px" class="loginForm" :model="form" :rules="rules">
        <h1 class="loginTitle">轻课·加特林</h1>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" @input="enabledLoginBtn"></el-input>
        </el-form-item>
        <el-form-item label="密码" class="itemPassword" prop="password" @keyup.enter.native="login">
          <el-input :type="this.form.isHide ? 'password' : 'text'" v-model="form.password"
                    @input="enabledLoginBtn"></el-input>
          <el-button type="text" icon="el-icon-view" :class="{ 'btn-view': true, disabled: form.isHide }"
                     @click="showPassword"></el-button>
        </el-form-item>
        <el-form-item class="text-right">
          <el-checkbox v-model="form.isSeven">七天免登录</el-checkbox>
        </el-form-item>
        <div class="formBtn">
          <el-button class="btn-login" type="primary" size="medium" :disabled="!form.isFilled" @click="login">登录
          </el-button>
        </div>
      </el-form>
    </el-main>
  </div>
</template>
<script>
  // import Nav from '@/nav/nav.vue';
  // import CONSTANT from '../../constant/common';
  import auth from '../../util/auth';

  export default {
    data() {
      return {
        form: {
          username: '',
          password: '',
          isSeven: false,
          isHide: true,
          isFilled: false,
        },
        rules: {
          username: [
            {
              required: true, message: '请输入用户名', trigger: 'blur',
            },
            {
              min: 6, max: 30, message: '长度到6-30个字符', trigger: 'blur',
            },
            {
              validator(rule, value, callback) {
                if (value.match(/[\u4e00-\u9fa5]/g)) {
                  callback(new Error('请勿输入中文'));
                } else {
                  callback();
                }
              },
            },
          ],
          password: [
            {
              required: true, message: '请输入密码', trigger: 'blur',
            },
            {
              min: 6, max: 16, message: '请使用6-16个字母、数字、下划线', trigger: 'blur',
            },
          ],
        },
      };
    },
    methods: {
      // 改变密码可见
      showPassword() {
        this.form.isHide = !this.form.isHide;
      },
      // 激活登录按钮
      enabledLoginBtn() {
        if (this.form.username && this.form.password) {
          this.form.isFilled = true;
          return;
        }
        this.form.isFilled = false;
      },
      // 登录
      login() {
        // todo
        const {isSeven} = this.form;
        this.$refs.form.validate().then(() => {
          this.$store.dispatch('postLogin', {
            username: this.form.username,
            password: this.form.password,
          }).then((res) => {
            console.log(res, 999)
            if (res && res.status === 500) {
              this.$message.error(res.message);
            } else {
              this.$message.success('登录成功！');
              // 第一次登录需要更改密码
              if (res.isFirstLogin) {
                this.$router.push({
                  path: '/setPassword',
                });
                return;
              }
              this.$store.dispatch('getWoaList').then((getWoaList) => {
                // 绑定信息
                auth.saveUserInfo(res, isSeven);
                // 超级管理员登录但未绑定公众号
                if (res.publicAccounts.length < 1 && res.role === 'ADMIN') {
                  this.$message({
                    type: 'warning',
                    message: '您暂未绑定公众号，现在跳转到公众号绑定',
                  });
                  this.$store.dispatch('setCurrentWoa', {
                    publicAccountNickname: '未知公众号',
                  });
                  this.$router.push({
                    path: '/wechat-offical-account',
                  });
                  return;
                }
                if (res.publicAccounts.length < 1 && res.role === 'USER') {
                  this.$message({
                    type: 'warning',
                    message: '当前账号无公众号，请联系管理员绑定公众号',
                  });
                  this.$store.dispatch('setCurrentWoa', {
                    publicAccountNickname: '未知公众号',
                  });
                  this.$router.push('/home');
                  return;
                }

                // 有公众号
                const woaList = getWoaList || [];
                this.$store.dispatch('setCurrentWoa', woaList[0]);
                this.$router.push({
                  path: '/home',
                });
              }, (err) => {
                this.$message.error(err.message);
              });
            }
          }, (err) => {
            console.log('login error ', err);
            this.$message.error(err.message);
          });
        });
      },
    },
    mounted() {
      const token = auth.getToken();
      const loginStatus = auth.getIsFirstLogin();
      if (!loginStatus) {
        auth.clearUserInfo();
        this.$router.push({
          path: '/',
        });
        return;
      }
      if (token) {
        this.$router.push({
          path: '/home',
        });
      }
    },
  };
</script>
<style lang="less">
  .loginTitle {
    text-align: center;
    text-indent: 50px;
  }

  .loginForm {
    max-width: 450px;
    margin: 0 auto;

    .itemPassword {
      position: relative;

      .btn-view {
        position: absolute;
        top: 0;
        right: 10px;

        &.disabled {
          color: #c0c4cc;
        }
      }
    }

    .formBtn {
      text-align: center;

      .btn-login {
        margin-left: 50px;
      }
    }

    .text-right {
      text-align: right;
    }
  }
</style>
